package ws

import (
	"kugo/log"
	"net/http"
	"strconv"

	"github.com/gorilla/websocket"
)

type WSConn interface {
	ConnSuccess(*SocketSingleton, interface{})
	CloseSocket(*SocketSingleton, interface{})
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		// 在这里进行来源检查，根据实际情况修改
		// 这个例子中，我们简单地允许所有来源
		return true
	},
}

var wsConn WSConn

func StartWSServer(port int, ws WSConn) error {
	wsConn = ws
	go func() {
		log.ErrLog("WS 服务启动")
		http.HandleFunc("/ws", handleConnections)
		err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
		if err != nil {
			log.ErrLog("WS 服务启动失败 %s", err.Error())
			panic(err)
		}
		log.ErrLog("WS 服务启动成功")
	}()
	return nil
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
	log.Debug("连接响应 0 ")
	userId := r.URL.Query().Get("token")
	log.Debug("Received token: %s", userId)
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.ErrLog(err.Error())
		return
	}
	log.Debug("连接响应 1 ")
	id, _ := strconv.ParseInt(userId, 10, 64)
	if SocketPoolInstance.getConnection(id) != nil {
		log.Debug("连接已存在 %d", id)
		wsConn.CloseSocket(SocketPoolInstance.getConnection(id), id)
		SocketPoolInstance.getConnection(id).Close()
		return
	}
	// 创建一个新的连接
	newSocket := newSocketSingleton(conn, SocketPoolInstance)
	newSocket.SetBind(id)
	// 将新连接添加到连接池
	SocketPoolInstance.addConnection(id, newSocket)
	conn.SetCloseHandler(func(code int, text string) error {
		// 在这里处理连接关闭事件
		log.ErrLog("连接关闭 code %d, reason: %s", code, text)

		// 在连接关闭时，从连接池中移除连接
		SocketPoolInstance.removeConnection(id)
		wsConn.CloseSocket(newSocket, id)
		// 在这里可以进行一些清理工作
		return nil
	})
	wsConn.ConnSuccess(newSocket, id)
	// 处理连接
	newSocket.handleConnection()
}

//得改成校验完成之后才算连接成功，并且连接池用ID来绑定对应的socket
